package com.yibo.yunpicture.interfaces.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yibo.yunpicture.infrastructure.annotation.AuthCheck;
import com.yibo.yunpicture.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yibo.yunpicture.infrastructure.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.yibo.yunpicture.infrastructure.api.aliyunai.sub.AliYunAiApi;
import com.yibo.yunpicture.infrastructure.api.imageSearch.ImageSearchApiFacade;
import com.yibo.yunpicture.infrastructure.api.imageSearch.model.ImageSearchDTO;
import com.yibo.yunpicture.interfaces.assembler.PictureAssembler;
import com.yibo.yunpicture.interfaces.dto.picture.*;
import com.yibo.yunpicture.shared.auth.SpaceUserAuthManager;
import com.yibo.yunpicture.shared.auth.StpKit;
import com.yibo.yunpicture.shared.auth.annotation.SaSpaceCheckPermission;
import com.yibo.yunpicture.shared.auth.model.SpaceUserPermissionConstant;
import com.yibo.yunpicture.infrastructure.common.BaseResponse;
import com.yibo.yunpicture.infrastructure.common.DeleteRequest;
import com.yibo.yunpicture.infrastructure.common.ResultUtils;
import com.yibo.yunpicture.domain.user.constant.UserConstant;
import com.yibo.yunpicture.infrastructure.exception.BusinessException;
import com.yibo.yunpicture.infrastructure.exception.ErrorCode;
import com.yibo.yunpicture.infrastructure.exception.ThrowUtils;
import com.yibo.yunpicture.domain.picture.entity.Picture;
import com.yibo.yunpicture.domain.space.entity.Space;
import com.yibo.yunpicture.domain.user.entity.User;
import com.yibo.yunpicture.domain.picture.valueobject.PictureReviewStatusEnum;
import com.yibo.yunpicture.interfaces.vo.picture.PictureTagCategory;
import com.yibo.yunpicture.interfaces.vo.picture.PictureVO;
import com.yibo.yunpicture.application.service.PictureApplicationService;
import com.yibo.yunpicture.application.service.SpaceApplicationService;
import com.yibo.yunpicture.application.service.UserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {
    @Resource
    private PictureApplicationService pictureApplicationService;

    @Resource
    private UserApplicationService userApplicationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    //构造本地缓存，设置缓存容量和过期时间
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();
    @Resource
    private SpaceApplicationService spaceApplicationService;

    /**
     * 通过文件上传图片
     *
     * @param multipartFile
     * @param pictureUploadDTO
     * @param request
     * @return
     */
    @PostMapping("/upload")
    // 必须有图片上传权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadDTO pictureUploadDTO, HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        PictureVO pictureVO = pictureApplicationService.uploadPicture(multipartFile, pictureUploadDTO, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过URL上传图片
     *
     * @param pictureUploadDTO
     * @param request
     * @return
     */
    @PostMapping("/upload/url")
    // 必须有图片上传权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadDTO pictureUploadDTO, HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        String fileUrl = pictureUploadDTO.getFileUrl();
        PictureVO pictureVO = pictureApplicationService.uploadPicture(fileUrl, pictureUploadDTO, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    // 必须要有图片删除权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        User loginUser = userApplicationService.getLoginUser(request);
        long id = deleteRequest.getId();
        pictureApplicationService.deletePicture(id, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员）
     *
     * @param pictureUpdateDTO
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateDTO pictureUpdateDTO, HttpServletRequest request) {
        if (pictureUpdateDTO == null || pictureUpdateDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //将实体类和DTO进行类型转换
        Picture picture = PictureAssembler.toPictureEntity(pictureUpdateDTO);
        //数据校验
        pictureApplicationService.validPicture(picture);
        //判断是否存在
        long id = pictureUpdateDTO.getId();
        Picture oldPicture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //补充审核参数
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.fillReviewParam(picture, loginUser);
        //操作数据库
        boolean result = pictureApplicationService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取图片
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPicture(Long id, HttpServletRequest request) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询数据库
        Picture picture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        //获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据id获取图片VO
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVO(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0 , ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureApplicationService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间权限校验
        Space space = null;
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            // 编程式权限校验
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.FORBIDDEN_ERROR);
            space = spaceApplicationService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        }
        // 获取权限列表
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(picture,space, loginUser);
        PictureVO pictureVO = pictureApplicationService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页查询图片(仅管理员有权限)
     *
     * @param pictureQueryDTO
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryDTO pictureQueryDTO) {
        ThrowUtils.throwIf(pictureQueryDTO == null, ErrorCode.PARAMS_ERROR);
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //查询数据库
        Page page = new Page<>(current, pageSize);
        QueryWrapper<Picture> queryWrapper = pictureApplicationService.getQueryWrapper(pictureQueryDTO);
        Page<Picture> picturePage = pictureApplicationService.page(page, queryWrapper);
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片封装列表
     *
     * @param pictureQueryDTO
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryDTO pictureQueryDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryDTO == null, ErrorCode.PARAMS_ERROR);
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryDTO.getSpaceId();
        // 公共图库
        if (spaceId == null) {
            pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryDTO.setNullSpaceId(true);
        } else {
            // 私有图库
            //User loginUser = userService.getLoginUser(request);
            //Space space = spaceService.getById(spaceId);
            //ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            //if (!space.getUserId().equals(loginUser.getId())) {
            //  throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            //}
            // 编程式校验
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.FORBIDDEN_ERROR);
        }
        //查询数据库
        Page page = new Page<>(current, pageSize);
        QueryWrapper<Picture> queryWrapper = pictureApplicationService.getQueryWrapper(pictureQueryDTO);
        Page<Picture> picturePage = pictureApplicationService.page(page, queryWrapper);
        //获取封装好的图片列表对象
        Page<PictureVO> pictureVOPage = pictureApplicationService.getPictureVOPage(picturePage, request);
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 通过查询缓存，分页获取图片封装列表
     *
     * @param pictureQueryDTO
     */
    @Deprecated
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryDTO pictureQueryDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryDTO == null, ErrorCode.PARAMS_ERROR);
        long current = pictureQueryDTO.getCurrent();
        long pageSize = pictureQueryDTO.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        //普通用户只能查看已经过审的图片
        pictureQueryDTO.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        // 1. 构建查询的key
        // 将pictureQueryDTO对象转换为JSON字符串
        String queryCondition = JSONUtil.toJsonStr(pictureQueryDTO);
        // 使用MD5算法生成hashKey
        String hashKey = DigestUtils.md5Hex(queryCondition);
        // 构建Redis缓存的key，进行拼接操作
        String cacheKey = "yun:listPictureVOByPage" + hashKey;

        String cacheValue = LOCAL_CACHE.getIfPresent(cacheKey);
        // 2. 从本地缓存查询获取图片列表
        if (cacheValue != null) {
            //如果缓存命中，返回结果
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(pictureVOPage);
        }
        // 3. 查询Redis分布式缓存
        ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
        cacheValue = valueOps.get(cacheKey);
        if (cacheValue != null) {
            //如果缓存命中，将Redis中的缓存结果存入到本地缓存中，返回结果
            LOCAL_CACHE.put(cacheKey, cacheValue);
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(pictureVOPage);
        }
        // 4. 如果二级缓存均未命中，查询数据库
        Page page = new Page<>(current, pageSize);
        QueryWrapper<Picture> queryWrapper = pictureApplicationService.getQueryWrapper(pictureQueryDTO);
        Page<Picture> picturePage = pictureApplicationService.page(page, queryWrapper);
        //获取封装好的图片列表对象
        Page<PictureVO> pictureVOPage = pictureApplicationService.getPictureVOPage(picturePage, request);
        // 更新缓存
        cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 更新本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 更新Redis缓存
        valueOps.set(cacheKey, cacheValue, 5, TimeUnit.MINUTES);
        // 返回结果
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片(给用户使用)
     *
     * @param pictureEditDTO
     * @return
     */
    @PostMapping("/edit")
    // 必须有图片编辑权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditDTO pictureEditDTO, HttpServletRequest request) {
        if (pictureEditDTO == null || pictureEditDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Picture picture = PictureAssembler.toPictureEntity(pictureEditDTO);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.editPicture(picture, loginUser);
        return ResultUtils.success(true);
    }

    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "风景", "人物",
                "高清", "艺术", "校园", "背景", "简历", "创意", "建筑", "动物");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewDTO pictureReviewDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewDTO == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.doPictureReview(pictureReviewDTO, loginUser);
        return ResultUtils.success(true);
    }

    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureBatch(@RequestBody PictureUploadByBatchDTO pictureUploadByBatchDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUploadByBatchDTO == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        int uploadPictureBatch = pictureApplicationService.uploadPictureBatch(pictureUploadByBatchDTO, loginUser);
        return ResultUtils.success(uploadPictureBatch);

    }

    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchDTO>> searchPicture(@RequestBody SearchPictureByPictureDTO searchPictureByPictureDTO) {
        ThrowUtils.throwIf(searchPictureByPictureDTO == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureDTO.getPictureId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureApplicationService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR);
        List<ImageSearchDTO> imageSearchDTOList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(imageSearchDTOList);
    }

    /**
     * 按颜色搜索图片
     */
    @PostMapping("/search/color")
    // 必须有图片查看权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorDTO searchPictureByColorDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorDTO == null, ErrorCode.PARAMS_ERROR);
        Long spaceId = searchPictureByColorDTO.getSpaceId();
        User loginUser = userApplicationService.getLoginUser(request);
        String picColor = searchPictureByColorDTO.getPicColor();
        List<PictureVO> pictureVOList = pictureApplicationService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 批量编辑图片
     */
    @PostMapping("/edit/batch")
    // 必须有图片编辑权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchDTO pictureEditByBatchDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchDTO == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        pictureApplicationService.editPictureByBatch(pictureEditByBatchDTO, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    // 必须有图片编辑权限
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskDTO createPictureOutPaintingTaskDTO,
                                                                                    HttpServletRequest request) {
        if (createPictureOutPaintingTaskDTO == null || createPictureOutPaintingTaskDTO.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userApplicationService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureApplicationService.createPictureOutPaintingTask(createPictureOutPaintingTaskDTO, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }
}
